var config = require('/config.js')
//  get 请求
function Get(url, headers, data, cb) {
  wx.showNavigationBarLoading();
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    method: 'GET',
    header: headers,
    url: config.HTTP_BASE_URL + url,
    data: data,
    success: (res) => {
      typeof cb == "function" && cb(res.data, res.statusCode);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    },
    fail: (err) => {
      typeof cb == "function" && cb(null, err.errMsg);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    }
  });
};

//  get 请求
function BaseGet(url, headers, data, cb) {
  wx.showNavigationBarLoading();
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    method: 'GET',
    header: headers,
    url: url,
    data: data,
    success: (res) => {
      typeof cb == "function" && cb(res.data, res.statusCode);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    },
    fail: (err) => {
      typeof cb == "function" && cb(null, err.errMsg);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    }
  });
};


//  post请求

function Post(url, headers, data, cb) {
  wx.showNavigationBarLoading();
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    method: 'POST',
    header: headers,
    url: config.HTTP_BASE_URL + url,
    data: data,
    success: (res) => {
      typeof cb == "function" && cb(res.data, res.statusCode);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    },
    fail: (err) => {
      typeof cb == "function" && cb(null, err.errMsg);
      console.log("http请求:" + config.HTTP_url);
      console.log(err)
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    }
  });
};

//  上传文件
function Upload(url, headers, file, data, cb) {
  wx.showNavigationBarLoading();
  wx.showLoading({
    title: '加载中...',
  })
  wx.uploadFile({
    url: config.HTTP_BASE_URL + url,
    header: headers,
    filePath: file,
    name: "files",
    formData: data,
    success: (res) => {
      if (typeof (res.data) == "string") {
        typeof cb == "function" && cb(
          JSON.parse(res.data), res.statusCode);
      } else {
        typeof cb == "function" && cb(res.data, "");
      }
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    },
    fail: (err) => {
      typeof cb == "function" && cb(null, err.errMsg);
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    }
  });
};

module.exports = {
  httpGet: Get,
  httpPost: Post,
  httpUpload: Upload,
  baseGet: BaseGet,
};
